﻿using System;
using System.Collections.Generic;
using System.Text;
using Tracy.CoreLib.Data;
using Tracy.CoreLib;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace Tracy.Agent.DownloaderAdapter
{
    public interface IDownloaderAdapter
    {
        bool AddToDownload(ResourceItem item);
        void KeepAlive();
        event EventHandler<EventArgsWithData> OnException;
        void ShutDown();
    }

    public abstract class AbstractDownloaderAdapter
    {
        [DllImport("User32.dll", EntryPoint = "PostMessage")]
        protected static extern int PostMessage(
        int hWnd,   //   handle   to   destination   window   
        int Msg,   //   message   
        int wParam,   //   first   message   parameter   
        int lParam   //   second   message   parameter   
        );

        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        protected static extern int SendMessage(int hwnd, int wMsg, int wParam, string lParam);

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        protected extern static int FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        protected extern static int FindWindowEx(
            int hWnd1,
            int hWnd2,
            string lpsz1,
            string lpsz2
        );

        protected const int WM_KEYDOWN = 0x0100;
        protected const int WM_SETTEXT = 0x000C;

        protected bool killThreadFlag = false;
        public virtual void ShutDown()
        {
            killThreadFlag = true;
        }

        private Process hostProcess = null;
        public virtual Process HostProcess
        {
            get { if (hostProcess == null) KeepAlive(); return hostProcess; }
            set { hostProcess = value; }
        }

        public virtual string HostProcessName
        {
            get
            {
                return Constants.CONST_APPLICATION_PROCESS_EMULE;
            }
        }
        
        public virtual string HostPath
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public virtual void KeepAlive()
        {
            Process[] results = Process.GetProcessesByName(HostProcessName);
            if (results.Length == 0)
            {
                //未找到宿主程序
                hostProcess = Process.Start(HostPath);
                hostProcess.WaitForInputIdle();
            }
            else
            {
                hostProcess = results[0];
            }
        }


    }
}
